<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="100px">
            <el-form-item label="柜子资产编号" prop="assetCode">
                <el-input v-model="queryParams.assetCode" placeholder="请输入柜子资产编号" clearable />
            </el-form-item>
            <el-form-item label="绑定门店编号" prop="bindShopCode">
                <el-input v-model="queryParams.bindShopCode" placeholder="请输入门店编号" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['produce:produce-plan:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['produce:produce-plan:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['produce:produce-plan:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getContainerAssetList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="containerAssetlList" @selection-change="handleSelectionChange"
            :default-sort="{ prop: 'id', order: 'descending' }">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column sortable label="id" align="center" prop="id" :show-overflow-tooltip="true" />
            <el-table-column label="冰柜资产编号" align="center" prop="assetCode" :show-overflow-tooltip="true" />
            <el-table-column label="绑定门店编号" align="center" prop="bindShopCode" :show-overflow-tooltip="true" />
            <!-- <el-table-column label="门店名称" align="center" prop="shopName" :show-overflow-tooltip="true" />
            <el-table-column label="运行状态" align="center" prop="runStatus" :show-overflow-tooltip="true" />
            <el-table-column label="偏移量" align="center" prop="offset" :show-overflow-tooltip="true" />
            <el-table-column label="报警信息" align="center" prop="alarmInfo" :show-overflow-tooltip="true" />
            <el-table-column label="品牌方" align="center" prop="offset" :show-overflow-tooltip="true" />
            <el-table-column label="地址" align="center" prop="address" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    {{ scope.row.province || ' ' }} {{ scope.row.city || ' ' }} {{ scope.row.district || ' ' }}
                </template>
            </el-table-column> -->
            <!-- <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" /> -->
            <!-- <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true" >
          <template slot-scope="scope">
            {{ parseTime(new Date(scope.row.createTime)) }}
          </template>
        </el-table-column> -->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">

                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-lock"
                        @click="handleBind(scope.row)">绑定设备</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit"
                        @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete"
                        @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getContainerAssetList" />

        <!-- 添加或修改冰柜资产对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="140px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="冰柜资产编号" prop="assetCode">
                            <el-input v-model="form.assetCode" placeholder="请输入" maxlength="20" show-word-limit />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="绑定门店编号" prop="bindShopCode">
                            <el-input v-model="form.bindShopCode" placeholder="请输入" maxlength="20" show-word-limit />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 绑定设备-检索部分 -->
        <el-dialog title="绑定设备" :visible.sync="bindVisible" width="60%">
            <el-form ref="searchingForm" :model="searchingForm">
                <el-form-item label="设备唯一id:" style="float:left;text-align:center;margin-left:3%">

                </el-form-item>
                <el-input v-model="searchingForm.deviceId" placeholder="请输入设备唯一id" clearable
                    style="width:200px;float: left;" />
                <el-form-item label="设备名称:" style="width:8%;float:left;text-align:center;margin-left:3%">

                </el-form-item>
                <el-input v-model="searchingForm.deviceName" placeholder="请输入设备名称" clearable style="width:200px" />
                <el-button type="primary" icon="el-icon-search" size="mini" style="margin-left:20px"
                    @click="getMainDeviceList">检索</el-button>
            </el-form>
            <!-- 绑定算法-结果部分 -->
            <el-table v-loading="bindLoading" :data="mainDevicelList" style="width: 100%" max-height="500"
                @selection-change="handleDeviceSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="设备唯一id" align="center" header-align="center" prop="deviceId" />
                <el-table-column label="设备名称" align="center" header-align="center" prop="name" />
                <el-table-column label="项目" align="center" header-align="center" prop="projectName" />
                <el-table-column label="设备组合" align="center" header-align="center" prop="deviceComposeName" />
            </el-table>
            <pagination v-show="devicePagn.total > 0" :total="devicePagn.total" :page.sync="devicePagn.pageNum"
                :limit.sync="devicePagn.pageSize" @pagination="getMainDeviceList" />
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelBind">取 消</el-button>
                <el-button type="primary" @click="confirmBind">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

import { listContainerAsset, getContainerAssetDetail, addContainerAsset, updateContainerAsset, exportContainerAsset, delContainerAsset, bindContainerAsset } from "@/api/container/containerAsset";
import { listMainDevice } from "@/api/device/mainDevice";
export default {
    name: "containerAsset",
    data() {
        return {
            // 表单数据
            form: {
                assetCode: null,
                bindShopCode: null,
                params:{
                    shopName:'fasdf',
                    runStatus:'345',
                    offset:'fasdf',
                    alarmInfo:'adsf',
                }
            },
            // 遮罩层
            loading: true,
            //获取绑定列表的遮罩层
            bindLoading: false,
            // 选中数组
            ids: [],
            // 选中项目名数组
            names: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 项目表格数据
            containerAssetlList: [],
            //绑定设备的列表数据
            mainDevicelList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            //绑定设备的弹出层
            bindVisible: false,
            //绑定设备的选择
            chooseValue: '',
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                orderByColumn: 'id',
                isAsc: 'desc'
            },
            //绑定设备的分页 
            devicePagn: {
                total: 0,
                pageNum: 1,
                pageSize: 10,
            },
            //绑定设备的查询参数
            searchingForm: {
                pageNum: 1,
                pageSize: 10,
                orderByColumn: 'id',
                isAsc: 'desc'
            },
            //要绑定设备的资产编号
            bindAssetCode: '',
            //冰柜资产详细信息列表
            DetailList: [],
            // 表单校验
            rules: {
                assetCode: [
                    { required: true, message: "冰柜资产编号不能为空", trigger: "blur" }
                ],
                bindShopCode: [
                    { required: true, message: "绑定门店编号不能为空", trigger: "blur" }
                ],
            }
        };
    },
    created() {
        this.getContainerAssetList();
    },
    methods: {
        /** 获取冰柜资产列表 */
        getContainerAssetList() {
            this.loading = true;
            listContainerAsset(this.queryParams).then((res) => {
                console.log("冰柜资产列表为", res)
                if (res.code === 200) {
                    this.containerAssetlList = res.rows
                    this.total = res.total
                }
            }).catch((err) => {
                this.$message.error("冰柜资产列表获取失败，原因：" + err.message)
            }).finally(() => {
                this.loading = false;
            })
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {}
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getContainerAssetList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.names = selection.map(item => item.model)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        //绑定设备全选
        handleDeviceSelectionChange(selection) {
            this.chooseValue = selection.map(item => item.deviceId)
            console.log('设备全选为', this.chooseValue);

        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加冰柜资产";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getContainerAssetDetail(id).then(response => {
                //todos 转类型 int
                this.form = response.data;
                this.form.coldHotType = parseInt(this.form.coldHotType)
                this.form.doorCount = parseInt(this.form.doorCount)
                this.form.doorDirectionLeft = parseInt(this.form.doorDirectionLeft)
                this.form.doorDirectionRight = parseInt(this.form.doorDirectionRight)
                this.open = true;
                this.title = "修改冰柜资产信息";
            });
        },
        /**绑定设备操作 */
        handleBind(row) {
            this.bindVisible = true;
            this.bindLoading = true;
            this.bindAssetCode = row.assetCode
            this.getMainDeviceList()
        },
        /**取消绑定 */
        cancelBind() {
            this.bindVisible = false
            this.getContainerAssetList()
        },
        /**绑定设备提交按钮操作 */
        confirmBind() {
            if (this.chooseValue) {
                //清除检索框的数值
                this.searchingForm.deviceId = ''
                this.searchingForm.deviceName = ''
                console.log('绑定设备为', JSON.parse(JSON.stringify(this.chooseValue)),);
                
                // todos modal关闭的时候清空 chooseValue
                //const chooseItem = this.getBindDataById(this.chooseValue)
                const params =
                {
                    assetCode: this.bindAssetCode,
                    deviceIdList:this.chooseValue.toString(),
                }
                this.bindLoading = true
                bindContainerAsset(params)
                    .then((res) => {
                        if (res.code == 200) {
                            this.$message.success("设备绑定成功！")
                            this.bindVisible = false
                            this.getContainerAssetList()
                        }else{
                            this.$message.error("设备绑定失败！")
                        }

                    })
                    .catch((err) => {
                        this.$message(err.message)
                    })
                    .finally(() => {
                        this.bindLoading = false
                    })
            } else {
                this.$message.error('请选择绑定设备')
             }
        },
        /**查询主设备列表 */
        getMainDeviceList() {
            const params = {
                pageNum: this.devicePagn.pageNum,
                pageSize: this.devicePagn.pageSize,
                deviceId: this.searchingForm.deviceId,
                name: this.searchingForm.name,
                orderByColumn: 'id',
                isAsc: 'desc'
            }
            listMainDevice(params).then((res) => {
                if (res.code === 200) {
                    this.mainDevicelList = res.rows
                    this.devicePagn.total = res.total
                }
            }).catch((err) => {
                this.$message.error("设备列表获取失败，原因：" + err.message)
            }).finally(() => {
                this.bindLoading = false;
            })
        },
        /** 提交按钮 */
        submitForm() {
            console.log("提交的form表单为", this.form)
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateContainerAsset(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getContainerAssetList();
                        });
                    } else {
                        addContainerAsset(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getContainerAssetList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            //todos 修改
            const ids = row.id || this.ids;
            const names = row.name || this.names
            this.$modal.confirm('是否确认删除冰柜资产名称名为"' + names + '"的数据项？').then(function () {
                // 修改为逻辑删除
                return delContainerAsset(ids);
            }).then(() => {
                this.getContainerAssetList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /**获取详细信息操作 */
        handleDetail(row) {
            const id = row.id
            getContainerAssetDetail(id).then(response => {
                this.DetailList = response.data;

            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('/genius/platform-container-asset/export', {
                ...this.queryParams
            }, `containerAssetlList_${new Date().getTime()}.xlsx`)
        }
    }
};
</script>

<style lang="scss">
.formTitle {
    width: 100%;
    text-align: center;
    margin: 15px 0 15px 0;
    font-weight: border;
    font-size: 20px
}
</style>